package com.itic.mall.system.orders.express.service;

import com.itic.appbase.applications.sys.syssetting.persistence.dao.SysSettingDao;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.system.inter.orders.express.persistence.dao.OrderExpressDao;
import com.itic.mall.system.inter.orders.express.persistence.model.OrderExpress;
import com.itic.mall.system.inter.orders.express.persistence.model.OrderExpressExample;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


@Service
@Transactional
public class OrderExpressService
     extends CrudService<OrderExpressDao,OrderExpress,OrderExpressExample> {
    
    
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
	//配置您申请的KEY
    public static final String APPKEY ="*************************";
    
    @Autowired
    private OrderExpressDao orderExpressDao;
    @Autowired
    private SysSettingDao sysSettingDao;

    /**
     * 根据快递类型的代码与订单号码，获取物流信息
     * @param code 物流代码
     * @param num  物流订单号码
     * @return
     */
    public Object getWuliuMsgByCodeAndNum( String code,String num ){
    	//添加物流信息
		String key = APPKEY;
		String byKey = sysSettingDao.getByKey("MALL_WULIU_KEY");
		if( StringHelper.isNotBlank(byKey) ){
			key = byKey;
		}
    	Object data = getRequest1( key, code, num );
    	return data;
    }
    
    //1.常用快递查询API
    public static Object getRequest1( String key, String wuliuType, String wuliuNum ){
    	Object result = null;
        String url ="http://v.juhe.cn/exp/index";//请求接口地址
        Map<String,Object> params = new HashMap<String,Object>();//请求参数
            params.put("com",wuliuType);//需要查询的快递公司编号
            params.put("no",wuliuNum);//需要查询的订单号
            params.put("key",key);//应用APPKEY(应用详细页查询)
            params.put("dtype","json");//返回数据的格式,xml或json，默认json
 
        try {
            result =net(url, params, "GET");
            JSONObject object = JSONObject.fromObject(result);
            if(object.getInt("error_code")==0){
            	JSONObject object2 = object.getJSONObject("result");
            	Object object3 = object2.get("list");
                result = object3;
            }else{
                result = object.get("error_code")+":"+object.get("reason");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
 
    /**
     *
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return  网络请求字符串
     * @throws Exception
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public static String net(String strUrl, Map params,String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                strUrl = strUrl+"?"+urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params!= null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                        out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }
 
    //将map型转为请求参数型
    @SuppressWarnings("rawtypes")
	public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}